

/*
 * @Author: 脉迈
 * @Date: 2022-01-18 17:05:36
 * @LastEditors: 脉迈
 * @LastEditTime: 2022-01-22 17:38:49
 */
module.exports = app=> ({
  async register(ctx,next){
    let {$models, $helper} = app
    let User = $models.User
    let {username,password} =  ctx.request.body
    
    await User.create({
      username: username,
      password: await $helper.createPassword(password)
    })
    .then((result) => {
      ctx.body = {
        message:'注册成功',
        code: 200
      }
    })
    .catch(err => {
      console.log(ctx.request.body)
      ctx.body = {
        message:'注册失s败',
        data:ctx.request.body,
        code: 500
      }
    })
    
  },
  async login(ctx,next){
    let {$models,$helper} = app
    let User = $models.User
    let {username} =  ctx.request.body
    const user = await User.findOne({ where: { username} });
    if (user === null) {
      console.log('Not found!');
      ctx.body = {
        message:'用户不存在,请确认后登录',
        data: {},
        code: 500
      }
    } else {
      console.log(user)
      let {username, password} = user.dataValues;
      if(await $helper.decodePassword(password) === ctx.request.body.password){
        ctx.body = {
          message:'登录成功',
          data:{
            token: await $helper.createToken({data:user.dataValues}),
            username
          },
          code: 200
        }
      }else{
        ctx.body = {
          message:'密码错误',
          data: {},
          code: 500
        }
      }
    }
  }
})